package cn.imvc.app.controllers;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.imvc.app.entities.Member;
import cn.imvc.app.models.CommissionModel;
import cn.imvc.app.models.DealerLevelModel;
import cn.imvc.app.models.DealerModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.util.ImageUtils;
import cn.imvc.util.QrCodeUtils;

@Controller
@RequestMapping("dealer")
public class DealerControllerImpl implements DealerController {

	@Autowired
	MemberModel memberModel;

	@Autowired
	DealerModel dealerModel;

	@Autowired
	DealerLevelModel dealerLevelModel;

	@Autowired
	CommissionModel commissionModel;

	@RequestMapping("/dealer.html")
	public String dealer(Model model, String token) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			member = memberModel.get(member.getId());
			int level = member.getDealer().getDealerLevel().getLevel();
			model.addAttribute("level", level);
			model.addAttribute("membercount", dealerModel.getMember(member).size());
			model.addAttribute("teamcount", dealerModel.getTeam(member).size());
//			if (type == (byte) 2) {
//				model.addAttribute("dealercount", dealerModel.getDealerCount(member).get(0));
//			}
			return "dealer/dealer";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("/team.html")
	public String team(Model model, String token, String type) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			member = memberModel.get(member.getId());
			if ("0".equals(type)) {
				model.addAttribute("sum", dealerModel.getMember(member).size());
			} else if ("1".equals(type)) {
				model.addAttribute("sum", dealerModel.getTeam(member).size());
//			} else if ("2".equals(type)) {
//				model.addAttribute("sum", dealerModel.getDealerCount(member).get(0));
			}
			model.addAttribute("type", type);
			return "dealer/team";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("/teamdetail.html")
	public String teamdetail(Model model, String token, int type) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			model.addAttribute("type", type);
			if(type == 1){
				model.addAttribute("totalconsumption", dealerModel.getTotalConsumption(member).get(0));
			}
			return "dealer/teamdetail";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("/pageteamdetail.html")
	@ResponseBody
	public Page<Object[]> pageteamdetail(Model model, String token, Integer page, String type) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			member = memberModel.get(member.getId());
			return commissionModel.findPageTeamDetail(member, page, type);
		} else {
			return null;
		}
	}

	@RequestMapping("/team.htm")
	public String pcteam(Model model, String token, String type, String page) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			member = memberModel.get(member.getId());
			if ("0".equals(type)) {
				model.addAttribute("sum", dealerModel.getMember(member).size());
			} else if ("1".equals(type)) {
				model.addAttribute("sum", dealerModel.getTeam(member).size());
				model.addAttribute("totalconsumption", dealerModel.getTotalConsumption(member).get(0));
//			} else if ("2".equals(type)) {
//				model.addAttribute("sum", dealerModel.getDealerCount(member).get(0));
			}
			model.addAttribute("type", type);
			model.addAttribute("page", page);
			return "dealer/pcteam";
		} else {
			return "redirect:/member/login.htm";
		}
	}

	@RequestMapping("/pageteamdetail.htm")
	public String pcpageteamdetail(Model model, String token, Integer page, String type) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			member = memberModel.get(member.getId());
			page--;
			PageRequest pageRequest = new PageRequest(page, 8, null);
			Page<Object[]> pageResult =  commissionModel.findPageTeamDetail(member, pageRequest, type);
			model.addAttribute("memberList", pageResult.getContent());
			model.addAttribute("count", pageResult.getTotalPages());
			model.addAttribute("type", type);
			return "dealer/pcteamdetail";
		} else {
			return "redirect:/member/login.htm";
		}
	}
	
	@RequestMapping("/getQrcode.htm")
	private ModelAndView createQrCode(String content, int width, int height,
            HttpServletResponse response) {
		if (content==null||"".equals(content)){
			return null;
		}
        BufferedImage bi = QrCodeUtils.encodePRToBufferedImage(content, width,
                height);
        try {
            response.setContentType("image/jpeg");
            OutputStream os = response.getOutputStream();
            ImageIO.write(bi, "jpg", os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(500);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
	
	@RequestMapping("/getQrcode.html")
	private ModelAndView createQrCode(String content, String loginname, String name, HttpServletResponse response) {
		if (content == null || "".equals(content)) {
			return null;
		}
		BufferedImage bi = ImageUtils.createPicTwo2(content, loginname, name);
		try {
			response.setContentType("image/jpeg");
			OutputStream os = response.getOutputStream();
			ImageIO.write(bi, "jpg", os);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.sendError(500);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
}
